//
//  OAuthViewController.swift
//  Weibo
//
//  Created by 鹏 周 on 15/12/13.
//  Copyright © 2015年 ycit. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking
import SDWebImage

class OAuthViewController: UIViewController {
    
    let webView = UIWebView()
    
    //关闭model出来的页面
    @objc private func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        loadOAuthPage()
        
        setNavBar()
        
    }
    
    @objc private func defaultAccount() {
        
        let jsString = "document.getElementById('userId').value = 'leiggee@126.com' ,document.getElementById('passwd').value = 'oyonomg' "
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    private func loadOAuthPage() {
    
    let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
//     let urlString = "http://webkk.chuanke.com/player/player_enc.swf"
    
        let url = NSURL(string: urlString)
        
        webView.loadRequest(NSURLRequest(URL: url!))
  
    }

    private func setNavBar() {
    self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "defaultAccount")
    
    }
    
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    
    
}

//extension 是相关的代码更加模块快  易与阅读和维护
extension OAuthViewController: UIWebViewDelegate {
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
        
        
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //request.URL为Optional(https://api.weibo.com/oauth2/authorize?client_id=1515018520&redirect_uri=http://www.baidu.com)
        
        guard let urlString = request.URL?.absoluteString else {
        return false
        }
        if urlString.hasPrefix("https://api.weibo.com") {
             //希望加载的页面
        return true
        }
        if !urlString.hasPrefix("http://www.baidu.com") {
            //一定不是请求成功后的回调  同样也不会是 我们希望加载的页面
        return false
        }
        let query = request.URL?.query
        if let q = query {
        let codeStr = "code="
        let code = q.substringFromIndex(codeStr.endIndex)
            print(code)
            loadAccessToken(code)
        }
        return true
    }
//    
//    private func loadAccessToken(code: String) {
//
//        UserAccountViewModel().loadAccessToken(code) { (isSuccess) -> () in
//            if isSuccess {
//            print("登陆成功")
//            
//            } else {
//            print("登陆失败")
//            }
//        }
//    
//    }
    
    
    // MARK:加载用户token(请求标识)
    func loadAccessToken(code:String) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let parameters = ["client_id":client_id,"client_secret":client_secret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri]
        
        let AFN = AFHTTPSessionManager()
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        AFN.POST(urlString, parameters: parameters, progress: { (p) -> Void in
//            print(p)
            }, success: { (_, result) -> Void in
                print("获取用户信息:\(result)")
                if let dict = result as? [String : AnyObject] {
//                    let token = dict["access_token"] as! String
//                    let uid = dict["uid"] as! String
                    //字典转模型
                    let userAccount = UserAccount(dict: dict)
                    self.loadUserInfo(userAccount)
                    
                }
            }) { (_, error) -> Void in
                print(error)
        }
    }
    
    // MARK:获取用户信息
//    private func loadUserInfo(token: String, uid: String) {
//        let urlString = "https://api.weibo.com/2/users/show.json"
//        let parameters = ["access_token": token, "uid": uid]
//        let AFN = AFHTTPSessionManager()
//        AFN.GET(urlString, parameters: parameters, progress: { (_) -> Void in
//            
//            }, success: { (_, result) -> Void in
//                print(result)
//                if let dict = result {
//                    let avatar_large = dict["avatar_large"] as! String
//                    let name = dict["name"] as! String
//                    print(avatar_large,name)
//                }
//            }) { (_, error) -> Void in
//                print(error)
//        }
//    }

    
    //MARK:获取用户信息
    func loadUserInfo(account: UserAccount) {
        let urlString = "https://api.weibo.com/2/users/show.json"
        if let token = account.access_token,userId = account.uid {
            let parameters  = ["access_token":token, "uid":userId]
            let AFN = AFHTTPSessionManager()
            
            AFN.GET(urlString, parameters: parameters, progress: { (_) -> Void in
                
                }, success: { (_, result) -> Void in
                    print("用户的信息为\(result)")
                    if let dict = result {
                        let avatar_large = dict["avatar_large"] as! String
                        let name = dict["name"] as! String
                        account.name = name
                        account.avatar_large = avatar_large
                    }
                    
                }, failure: { (_, error) -> Void in
                    print(error)
            })
            
        }
        
    }
    
    
}

